package com.bytz.modules.cms.domain.impl.price;

import com.bytz.modules.cms.domain.ProductPriceComputer;
import com.bytz.modules.cms.domain.model.price.PriceComputeContext;
import com.bytz.modules.cms.domain.model.price.PriceComputeResult;
import com.bytz.modules.cms.reseller.entity.ResellerLevel;
import com.bytz.modules.cms.reseller.entity.ResellerProduct;
import com.bytz.modules.cms.reseller.service.IResellerLevelService;
import com.bytz.modules.cms.reseller.service.IResellerProductService;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public abstract class AbstractPriceComputer implements ProductPriceComputer {
    @Override
    public void afterCompute(PriceComputeContext context) {
        // 设置还有价格的商品
        // 设置是否还需要继续
        if (context.getNeedContinue()) {
            context.setNeedContinue(!context.getHasPricePns().isEmpty());
        }
    }

    /**
     * 确保经销商独占优惠数据
     * 因为有多个Computer需要使用，写个公用方法只查一次
     *
     * @param resellerProductService 查询服务
     * @param context                上下文
     */
    protected void ensureResellerProducts(IResellerProductService resellerProductService, PriceComputeContext context) {
        if (context.getResellerProducts() == null) {
            List<ResellerProduct> resellerProducts = resellerProductService.getByResellerAndProductNumbers(context.getInputResellerId(), context.getHasPricePns());
            context.setResellerProducts(resellerProducts);
        }
    }

    /**
     * 确保经销商等级数据
     * 因为有多个Computer需要使用，写个公用方法只查一次
     *
     * @param resellerLevelService 查询服务
     * @param context              上下文
     */
    protected void ensureResellerLevels(IResellerLevelService resellerLevelService, PriceComputeContext context) {
        if (context.getResellerLevelMap() == null) {
            List<ResellerLevel> resellerLevels = resellerLevelService.getByResellerId(context.getInputResellerId());

            Map<String, String> resellerLevelMap = resellerLevels.stream()
                    .collect(Collectors.toMap(ResellerLevel::getProductLineId, ResellerLevel::getProductLineLevelId));

            context.setResellerLevelMap(resellerLevelMap);

            // 设置结果中的产品线等级Id
            for (PriceComputeResult value : context.getResults().values()) {
                value.setProductLineLevelId(resellerLevelMap.get(value.getProductLineId()));
            }
        }
    }


}